package com.Lyf.manager.controller;


import com.google.code.kaptcha.impl.DefaultKaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
public class CaptchaController {

    private Map<String, String> captchaMap = new HashMap<>();

    @Autowired
    private DefaultKaptcha captchaProducer;


    @GetMapping("/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 生成验证码文本
        String captchaText = captchaProducer.createText();
        log.debug("生成的验证码为 captchaText: {}", captchaText);
        // 根据文本生成验证码图片
        BufferedImage captchaImage = captchaProducer.createImage(captchaText);
        // 将验证码文本存储起来，这里以当前请求的session id作为键
        captchaMap.put(request.getSession().getId(), captchaText);
        // 设置响应头，告诉浏览器这是一张图片
        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
        ImageIO.write(captchaImage, "jpg", response.getOutputStream());
        response.getOutputStream().flush();
    }
}
